package com.ruoyi.ai.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.ai.service.ChatService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2025/3/19
 */
@RestController
public class ChatController {
    @Autowired
    private ChatService chatService;

    private final OpenAiChatModel chatModel;

    @Autowired
    public ChatController(OpenAiChatModel chatModel) {
        this.chatModel = chatModel;
    }

//    @GetMapping("/chat/stream")
//    public Flux<ServerSentEvent<String>> chat(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
//        Prompt prompt = new Prompt(new UserMessage(message));
//        return chatModel.stream(prompt)
//                .map(res -> {
//                    String content = res.getResults().get(0).getOutput().getText();
//                    return ServerSentEvent.<String>builder()
//                            .event("chat")  // 设置事件名称为chat
//                            .data(content)  // 将数据转换为JSON字符串
//                            .build();
//                });
//    }

    @GetMapping("/chat/stream")
    public Flux<ServerSentEvent<String>> chat(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return chatService.chatWithTools(message).map(res -> {
            String content = res.getResults().get(0).getOutput().getText();
            return ServerSentEvent.<String>builder()
                    .event("chat")  // 设置事件名称为chat
                    .data(content)  // 将数据转换为JSON字符串
                    .build();
        });
    }
}